import { routerRedux } from 'dva/router';
import material from '../../services/cms/material';

export default {
  namespace: 'material',

  state: {
    info: {},
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const params = payload
        ? {
            id: payload.id,
            page: payload.currentPage,
            size: payload.pageSize,
            name: payload.name,
            url: payload.url,
            description: payload.description,
          }
        : {};
      let response;

      if (params.id) {
        response = yield call(material.info, { ...params });
        yield put({
          type: 'info',
          payload: response.data,
        });
      } else {
        response = yield call(material.query, { ...params });
        response.data.list.forEach(item => {
          const o = item;
          o.key = item.id;
        });

        yield put({
          type: 'list',
          payload: response.data,
        });
      }
    },
    *add({ payload, callback }, { call }) {
      const response = yield call(material.add, { ...payload });
      console.log(response);
      if (callback) callback();
    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(material.update, { ...payload });
      if (response.code === 0) {
        yield put(routerRedux.push('/news/article'));
      }
      if (callback) callback();
    },
    *remove({ payload, callback }, { call }) {
      const response = yield call(material.remove, { ...payload });
      if (callback) callback(response);
    },
  },

  reducers: {
    list(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    info(state, action) {
      return {
        ...state,
        info: action.payload,
      };
    },
  },
};
